package org.example.service;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.mapper.UserMapper;
import org.example.pojo.User;
import org.example.util.SqlSessionFactoryUtils;

import java.io.IOException;
import java.io.InputStream;

public class UserService {

    //2.1获取SQLSessionFactory对象

    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
    public User login(String username, String password){
        //2.调用Mybatis
        //静态代码块会随着类的加载而自动执行，且执行一次

        //2.2获取SQLSession对象
        SqlSession session = sqlSessionFactory.openSession();
        //2.3获取Mapper
        UserMapper mapper = session.getMapper(UserMapper.class);

        //2.4调用方法
        User user = mapper.select(username, password);
        //2.5释放资源
        session.close();
        return user;

    }

   public boolean register(User user){

       //2.调用Mybatis

       //2.2获取SQLSession对象
       SqlSession session = sqlSessionFactory.openSession();
       //2.3获取Mapper
       UserMapper mapper = session.getMapper(UserMapper.class);

       //判断用户名是否存在
       User user1 = mapper.selectUser(user.getUsername());

       if(user1 == null){
           mapper.insert(user);
           session.commit();
       }
       session.close();
       return user1 == null;
   }
}
